<template>
    <!-- 信用量管理 -->
    <div>
        <section class="business-wrapper">
            <el-form
                    ref="form"
                    :model="queryForm"
                    label-width="80px"
                    :inline="true"
                    class="queryForm"
                    :class="{'more': showMore, 'less': !showMore}"
            >

                <el-row class="more-content">
                    <el-form-item label="日期:">
                        <el-radio-group v-model="ckecked" @change="changeTime">
                            <el-radio-button label="1">今日</el-radio-button>
                            <el-radio-button label="2">本周</el-radio-button>
                            <el-radio-button label="3">本月</el-radio-button>
                            <el-radio-button label="4">上月</el-radio-button>
                            <el-radio-button label="5">本年</el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="自定义:" class="customized">
                        <el-date-picker
                                v-model="queryForm.dateTime"
                                type="datetimerange"
                                :picker-options="pickerOptions"
                                range-separator="至"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                align="right">
                        </el-date-picker>
                    </el-form-item>
                </el-row>
                                            <el-row class="business-status">
                                <el-form-item label="状态:">
                                    <el-radio-group v-model="queryForm.state">
                                        <el-radio-button :label="item.value" :key="item.value"
                                                         v-for="item in  $dictUtils.getDictList('state')">
                                            {{ item.label }}
                                        </el-radio-button>
                                    </el-radio-group>
                                </el-form-item>
                            </el-row>

                <el-row class="business-status">
                    <el-form-item label="关键字:">
                        <el-input
                                v-model="queryForm.keyWord"
                                size="large"
                                style="width: 400px"
                                placeholder="请输入关键字"
                        ></el-input>
                    </el-form-item>
                </el-row>
                <el-row class="more-content getMoney-type">
                    <el-form-item label="收款方式:">
                        <el-radio-group v-model="queryForm.getMoneyType">
                            <el-radio-button :label="item.value" :key="item.value"
                                             v-for="item in  $dictUtils.getDictList('getMoneyType')">{{ item.label }}
                            </el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                    <el-row class="business-status">
                        <el-form-item label="状态:">
                            <el-radio-group v-model="queryForm.state">
                                <el-radio-button :label="item.value" :key="item.value"
                                                 v-for="item in  $dictUtils.getDictList('state')">
                                    {{ item.label }}
                                </el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                    </el-row>

                </el-row>
                <el-row class="more-content company-name">
                </el-row>
                <el-row class="btn-content">
                    <el-form-item>
                        <div class="but-container">
                            <el-button
                                    type="primary"
                                    size="small"
                                    style="margin-right:5px"
                                    @click="
                getList(
                  page,
                  orderBy.name,
                  orderBy.method,
                  queryForm.dateTime,
                  queryForm.state,
                  queryForm.companyName,
                  queryForm.productId,
                  queryForm.dataType,
                  queryForm.keyWord
                )">查询
                            </el-button>
                            <el-button size="small" @click="reset">重置</el-button>
                            <div class="more-button" @click="handleShowMore">更多筛选条件<i
                                        :class="{ 'el-icon-arrow-up' : this.showMore , 'el-icon-arrow-down': !this.showMore}"></i>
                            </div>
                        </div>
                    </el-form-item>
                </el-row>
            </el-form>
        </section>
        <div class="btn-wrapper">
            <el-button type="primary" v-if="hasPermission('test:productMapping:add')"
                       @click="goToAddForm" size="small">新增</el-button>
            <el-button size="small" v-if="hasPermission('test:productMapping:delete')"
                       @click="del">删除</el-button>
            <el-button size="small" @click="exportExcel(processType,
                  page,
                  orderBy.name,
                  orderBy.method,
                  queryForm.dateTime,
                  queryForm.state,
                  queryForm.getMoneyType,
                  queryForm.companyName,
                  queryForm.productId,
                  queryForm.modelId,
                  queryForm.dataType,
                  queryForm.keyWord)">导出
            </el-button>
        </div>
        <el-table
                size="mini"
                v-loading="loading"
                :data="tableData"
                style="width: 100%; margin-top: 10px"
                border
                :header-cell-style="{
        'background-color': '#eeeeee !important',
      }"
                :row-class-name="tableRowClassName"
                @selection-change="tableSelected"
                @sort-change="sortthiscolumn">
            <el-table-column
                    type="selection"
                    width="60">
            </el-table-column>
            <el-table-column type="index" label="序号" width="70" align="center">
                <template slot-scope="scope">
          <span>{{
              (page.pageNo - 1) * page.pageSize + scope.$index + 1
            }}</span>
                </template>
            </el-table-column>
                        <el-table-column prop="sourceCategoryId"  label="源货物分类ID"></el-table-column>
                        <el-table-column prop="sourceProductId"  label="源货物ID"></el-table-column>
                        <el-table-column prop="targetCategoryId"  label="目标货物分类ID"></el-table-column>
                        <el-table-column prop="targetProductId"  label="目标货物ID"></el-table-column>
                        <el-table-column prop="state" label="状态"  sortable="custom" width="100px" align="center">
                            <template slot-scope="scope">
                                <section class="activate-state" v-if="scope.row.state===1">
                                    <i></i>
                                     {{$dictUtils.getDictLabel("state", scope.row.state, "")}}
                                </section>
                                <section class="inactive-state" v-else>
                                    <i></i>
                                    {{$dictUtils.getDictLabel("state", scope.row.state, "")}}
                                </section>
                            </template>
                        </el-table-column>
                        <el-table-column prop="effectTimeStamp"  label="生效时间戳"></el-table-column>

            <span v-for="(item, index) in checkedProps" :key="index">
        <el-table-column  prop="createDate" :label="item" v-if="item==='创建时间'"></el-table-column>
          <el-table-column  prop="createBy.loginName" :label="item" v-if="item==='创建人'"></el-table-column>
          <el-table-column  prop="updateDate" :label="item" v-if="item==='上次操作时间'"></el-table-column>
          <el-table-column  prop="updateBy.loginName" :label="item" v-if="item==='上次操作人'"></el-table-column>
      </span>

            <el-table-column prop="address" label="操作" width="252">
                <template slot-scope="scope">
                    <template v-for="item in $dictUtils.getDictList('state')">
                        <el-link type="primary" v-if="item.value !=='-1'&&hasPermission('test:productMapping:edit')&& item.value!==(scope.row.state+'')"
                                 :underline="false" @click="editState(item.value,scope.row)" :disabled="(scope.row.state===-1&& item.value==='0')||item.value==scope.row.state">{{item.label}}
                        </el-link>
                    </template>
                    <el-link type="primary" :underline="false" @click="edit(scope.row)"
                             v-if="hasPermission('test:productMapping:edit')"
                    >修改
                    </el-link
                    >
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :page-size="page.pageSize"
                :current-page="page.pageNo"
                layout="total,sizes,prev, pager, next, jumper"
                :total="page.total"
        >
        </el-pagination>
        <EditForm
                ref="EditForm"
                @refreshDataList="getList(page, orderBy.name, orderBy.method)"
        ></EditForm>



    </div>
</template>
<script>
    import {getList, del, updateState} from '@/api/product/mapping/ProductMapping.js';
    import EditForm from './ProductMappingEditForm'
    import PopoverBut from '@/components/button/popoverBut'
    const options1 = []
    const cityOptions = ['上海', '北京']
    export default {
        components: {
            EditForm,
            PopoverBut
        },
        data() {
            return {
                processType: 1, // 业务流程类型 1: 销售
                businessIds: [], // 选中的数据id数组
                modelIds: [], // 选中的数据modelId数组
                processTypeData: [],
                ckecked: '',
                showMore: false,
                queryForm: {
                    keyWord: '',
                    modelId: '',
                    dateTime: '',
                    state: '',
                    getMoneyType: '',
                    dataType: '',
                    contractCode: '',
                    companyId: '',
                    companyName: '',
                    productId: '',
                    productName: '',
                    checkedState: '1',
                    name: ''
                },
                pickerOptions: { // 时间选项
                    shortcuts: [{
                        text: '近7日',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                            picker.$emit('pick', [start, end])
                        }
                    }, {
                        text: '近15日',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 15)
                            picker.$emit('pick', [start, end])
                        }
                    }, {
                        text: '近30日',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                            picker.$emit('pick', [start, end])
                        }
                    }]
                },
                value2: '',
                checkedProps: options1,
                ShowCloum: {createDate: ''},
                options: [
                    {label: '上次操作时间', key: '2'},
                    {label: '创建时间', key: 'createDate'}
                ],
                tableData: [],
                orderBy: {
                    name: 'create_date',
                    method: 'desc'
                },
                loading: false,
                page: {
                    pageSize: 10,
                    pageNo: 1,
                    total: 0
                },
                props: 1,
                checkedCities: [],
                cities: cityOptions
            }
        },
        methods: {
            // 多选
            tableSelected(val) {
                // 去重获取被选中的id值存入到数组中
                this.businessIds = []
                this.modelIds = []
                for (let selectedItem of val) {
                    this.businessIds.push(selectedItem.id)
                    this.modelIds.push(selectedItem.modelId)
                }
            },

            // 导出
            exportExcel(processType, params, orderName, orderByAORC, queryDateTime, queryState, getMoneyType, companyName, productId, modelId, dataType, keyWord) {
                this.$http({
                    method: 'get',
                    url: '/business/export',
                    params: {
                        processType: processType,
                        pageSize: params.pageSize,
                        pageNo: params.pageNo,
                        orderBy: orderName,
                        orderByAORC: orderByAORC,
                        contractStartDate: queryDateTime == null ? null : queryDateTime[0],
                        contractEndDate: queryDateTime == null ? null : queryDateTime[1],
                        state: queryState,
                        getMoneyType: getMoneyType,
                        companyName: companyName,
                        productId: productId,
                        modelId: modelId,
                        dataType: dataType,
                        keyWord: keyWord
                    },
                    responseType: 'blob'
                }).then(response => {
                    if (!response) {
                        return
                    }
                    let link = document.createElement('a')
                    link.href = window.URL.createObjectURL(new Blob([response.data]))
                    link.target = '_blank'
                    let filename = response.headers['content-disposition']
                    link.download = decodeURI(filename)
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link)
                    // eslint-disable-next-line handle-callback-err
                }).catch((error) => {

                })
            },
            // 改变状态
            editState (state, row) {
                this.$confirm('是否修改状态?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then((res) => {
                    updateState({id: row.id, state: state}).then(res => {
                        if (res.data.code === '200') {
                            this.$message({
                                type: 'success',
                                message: '状态修改成功'
                            })
                            this.getList(this.page, this.orderBy.name, this.orderBy.method)
                        }
                    })
                })
            },
            // 删除业务
            del() {
                if (this.businessIds.length != 0) {
                  this.$confirm('是否批量删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then((res) => {
                    var str = ''
                    for (var i = 0; i < this.businessIds.length; i++) {
                      str += this.businessIds[i] + ','
                    }
                    // 去掉最后一个逗号(如果不需要去掉，就不用写)
                    if (str.length > 0) {
                      str = str.substr(0, str.length - 1)
                    }
                    this.loading = true
                    del({
                      ids: str
                    }).then((res) => {
                      if (res.data.code === '200') {
                        this.getList(this.processType, this.page, this.orderBy.name, this.orderBy.method)
                        this.$message({
                          type: 'success',
                          message: '删除成功'
                        })
                      } else {
                        this.$message({
                          type: 'error',
                          message: res.data.message
                        })
                      }
                      this.loading = false
                    })
                  })
                } else {
                  this.$notify.error({
                    title: '错误',
                    message: '请选择数据'
                  })
                }
            },
            goToAddForm() {
                this.$router.push({path: './addBusinessView'})
            },
            // 编辑
            edit (row) {
                this.$refs.EditForm.init('edit', row)
            },
            changeTime(value) {
                this.ckecked = value
                if (value === '1') {
                    const start = new Date(new Date(new Date().toLocaleDateString()).getTime())
                    const end = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)
                    this.queryForm.dateTime = [start, end]
                }
                if (value === '2') {
                    const start = getMonday('s', 0)
                    const end = getMonday('e', 0)
                    const newStart = start + ' 00:00:00'
                    const newEnd = end + ' 23:59:59'
                    this.queryForm.dateTime = [newStart, newEnd]
                }
                if (value === '3') {
                    const start = getMonth('s', 0)
                    const end = getMonth('e', 0)
                    const newStart = start + ' 00:00:00'
                    const newEnd = end + ' 23:59:59'
                    this.queryForm.dateTime = [newStart, newEnd]
                }
                if (value === '4') {
                    const start = getMonth('s', -1)
                    const end = getMonth('e', -1)
                    const newStart = start + ' 00:00:00'
                    const newEnd = end + ' 23:59:59'
                    this.queryForm.dateTime = [newStart, newEnd]
                }
                if (value === '5') {
                    const start = getYear('s', 0)
                    const end = getYear('e', 0)
                    const newStart = start + ' 00:00:00'
                    const newEnd = end + ' 23:59:59'
                    this.queryForm.dateTime = [newStart, newEnd]
                }
            },
            // 获取列表带分页
            getList(params, orderName, orderByAORC, queryDateTime, queryState, companyName, productId, dataType, keyWord) {
                this.loading = true
                getList({
                    pageSize: params.pageSize,
                    pageNo: params.pageNo,
                    orderBy: orderName,
                    orderByAORC: orderByAORC,
                    contractStartDate: queryDateTime == null ? null : queryDateTime[0],
                    contractEndDate: queryDateTime == null ? null : queryDateTime[1],
                    state: queryState,
                    companyName: companyName,
                    productId: productId,
                    dataType: dataType,
                    keyWord: keyWord
                }).then((res) => {
                    if (res.data.code === '200') {
                        this.tableData = res.data.result.list
                        this.page.total = res.data.result.count
                    }
                    this.loading = false
                })
            },
            reset() {
                this.queryForm.modelId = '',
                    this.queryForm.dateTime = '',
                    this.queryForm.state = '',
                    this.queryForm.getMoneyType = '',
                    this.queryForm.dataType = '',
                    this.queryForm.contractCode = '',
                    this.queryForm.companyId = '',
                    this.queryForm.companyName = '',
                    this.queryForm.productId = '',
                    this.queryForm.productName = '',
                    this.queryForm.checkedState = '',
                    this.queryForm.name = ''
            },
            // 排序
            sortthiscolumn(a) {
                this.orderBy.name = a.prop
                this.page.pageNo = 1
                if (a.order === 'ascending') {
                    this.orderBy.method = 'asc'
                } else {
                    this.orderBy.method = 'desc'
                }
                this.getList(this.page, this.orderBy.name, this.orderBy.method)
            },
            handleSizeChange(e) {
                this.page.pageSize = e
                this.getList(this.page, this.orderBy.name, this.orderBy.method)
            },
            handleCurrentChange(e) {
                this.page.pageNo = e
                this.getList(this.page, this.orderBy.name, this.orderBy.method)
                console.log(e)
            },
            tableRowClassName({row, rowIndex}) {
                if (rowIndex % 2 === 1) {
                    return 'warning-row'
                } else {
                    return 'success-row'
                }
            },
            // 显示更多筛选条件
            handleShowMore() {
                this.showMore = !this.showMore
            }
        },
        mounted() {
            this.getList(this.page, this.orderBy.name, this.orderBy.method)
        }
    }
    // 得到本周、上周、下周的起始、结束日期
    // getMonday(type,dates)  //type为字符串类型，有两种选择，"s"代表开始,"e"代表结束，dates为数字类型，不传或0代表本周，-1代表上周，1代表下周
    // getMonday("s",1)  //得到下周一的yyyy-mm-dd格式日期
    // getMonday("e",1)  //得到下周日的yyyy-mm-dd格式日期
    function getMonday(type, dates) {
        var now = new Date()
        var nowTime = now.getTime()
        var day = now.getDay()
        var longTime = 24 * 60 * 60 * 1000
        var n = longTime * 7 * (dates || 0)
        if (type == 's') {
            var dd = nowTime - (day - 1) * longTime + n
        }
        ;
        if (type == 'e') {
            var dd = nowTime + (7 - day) * longTime + n
        }
        ;
        dd = new Date(dd)
        var y = dd.getFullYear()
        var m = dd.getMonth() + 1
        var d = dd.getDate()
        m = m < 10 ? '0' + m : m
        d = d < 10 ? '0' + d : d
        var day = y + '-' + m + '-' + d
        return day
    };
    // 得到本月、上月、下月的起始、结束日期
    // getMonth(type,months)  //type为字符串类型，有两种选择，"s"代表开始,"e"代表结束，months为数字类型，不传或0代表本月，-1代表上月，1代表下月
    // getMonth("s",1)  //得到下月第一天的yyyy-mm-dd格式日期
    // getMonth("e",1)  //得到下月最后一天的yyyy-mm-dd格式日期
    function getMonth(type, months) {
        var d = new Date()
        var year = d.getFullYear()
        var month = d.getMonth() + 1
        if (Math.abs(months) > 12) {
            months = months % 12
        }
        ;
        if (months != 0) {
            if (month + months > 12) {
                year++
                month = (month + months) % 12
            } else if (month + months < 1) {
                year--
                month = 12 + month + months
            } else {
                month = month + months
            }
            ;
        }
        ;
        month = month < 10 ? '0' + month : month
        var date = d.getDate()
        var firstday = year + '-' + month + '-' + '01'
        var lastday = ''
        if (month == '01' || month == '03' || month == '05' || month == '07' || month == '08' || month == '10' || month == '12') {
            lastday = year + '-' + month + '-' + 31
        } else if (month == '02') {
            if ((year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0)) {
                lastday = year + '-' + month + '-' + 29
            } else {
                lastday = year + '-' + month + '-' + 28
            }
            ;
        } else {
            lastday = year + '-' + month + '-' + 30
        }
        ;
        var day = ''
        if (type == 's') {
            day = firstday
        } else {
            day = lastday
        }
        ;
        return day
    };

    // 得到今年、去年、明年的开始、结束日期
    // getYear(type,dates)  //type为字符串类型，有两种选择，"s"代表开始,"e"代表结束，dates为数字类型，不传或0代表今年，-1代表去年，1代表明年
    // getYear("s",1)  //得到明年第一天的yyyy-mm-dd格式日期
    // getYear("e",1)  //得到明年最后一天的yyyy-mm-dd格式日期
    function getYear(type, dates) {
        var dd = new Date()
        var n = dates || 0
        var year = dd.getFullYear() + Number(n)
        if (type == 's') {
            var day = year + '-01-01'
        }
        ;
        if (type == 'e') {
            var day = year + '-12-31'
        }
        ;
        if (!type) {
            var day = year + '-01-01/' + year + '-12-31'
        }
        ;
        return day
    };
</script>
<style lang="scss" scoped>
    .business-wrapper {

    ::v-deep.el-form {

    .more-content {
        display: none;
    }

    .el-row {

    .el-form-item {
        margin: 0;
    }

    .el-radio-button__inner {
        background: #FFFFFF;
        border-radius: 4px;
        font-size: 16px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        padding: 6px 9px;
        border: 1px solid transparent;
        color: #333333;
        margin-right: 10px;
        vertical-align: middle;
    }

    .el-radio-button__orig-radio:checked + .el-radio-button__inner, .el-radio-button__inner:hover {
        border: 1px solid #1890FF;
        color: #1890FF;
        box-shadow: none;
    }

    }
    .el-row.btn-content {

    .but-container {

    .more-button {
        display: inline-block;
        margin-left: 47px;
        font-size: 12px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #666666;
        cursor: pointer;
        vertical-align: top;
    }

    }
    }
    .el-row.getMoney-type {

    .el-form-item:first-child {
        margin-right: 197px;
    }

    }
    .el-row.company-name {

    .el-form-item:first-child {
        margin-right: 30px;
    }

    .el-form-item__label {
        line-height: 36px;
    }

    }
    }
    ::v-deep.el-form.more {

    .el-row.business-status {

    .el-input__inner {
        width: 350px;
    }

    }
    .el-row:first-child, .el-row.business-status, .el-row.getMoney-type {
        margin-bottom: 13px;
    }

    .el-row:nth-child(2) {
        margin-bottom: 20px;
    }

    .el-row.company-name, .el-row.btn-content {
        margin-bottom: 20px;
    }

    .more-content {
        display: block;
    }

    .el-row.btn-content {
        padding-left: 460px;
    }

    .el-input.el-input-group {

    input {
        width: 312px;
    }

    }
    }
    ::v-deep.el-form.less {

    .el-row {
        margin-bottom: 13px;
    }

    .btn-content {
        position: absolute;
        bottom: 0;
        left: 784px;
        margin-bottom: 0;

    .el-form-item {
        margin-bottom: 0;
    }

    }
    .business-status {
        margin-bottom: 20px;

    .el-form-item {
        margin-bottom: 0;

    .el-input__inner {
        width: 350px;
    }

    }
    }
    }
    }
    .btn-wrapper {

    .btn-set {
        width: 85px;
    }

    }
    ::v-deep.el-table {

    th:nth-child(2) .cell, td:nth-child(2) .cell {
        padding: 0 !important;
    }

    .cell {

    p {
        margin: 0 0 8px;
    }

    .mark {
        display: inline-block;
        width: 20px;
        height: 20px;
        border-radius: 4px;
        line-height: 18px;
        text-align: center;
        font-size: 12px;
        margin-right: 11px;
        vertical-align: bottom;
    }

    .mark.total {
        border: 1px solid #666666;
        color: #666666;
    }

    .mark.surplus {
        border: 1px solid #F59A23;
        color: #F59A23;
    }

    }
    }
    .queryForm {
        position: relative;
    }

    .right-but {
        float: right;
        margin-right: 10px;
        margin-top: -20px;
    }
</style>
